<script setup lang="ts">
import { reactive, ref } from "vue";
import { useRoute } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { updateDept, saveDept, findParentDeptById } from "@/api/admin/dept";
const type = ref('creat')
const props = defineProps({
  listData: Array
})
const route = useRoute();
type FormModel = {
  parentId: any;
  deptName: string;
  description: any;
  id: any;
};

  
const emit = defineEmits<{
  (event: "update"): void;
  (event: "handleSave", payload: { form: FormModel; type?: string }): void;
}>();
const dialogFormVisible = ref(false);
const ruleFormRef = ref<FormInstance>();
const form = reactive<FormModel>({
  deptName: "",
  description: "",
  parentId: undefined,
  id: undefined,
});
const rules: FormRules<FormModel> = {
  parentId: [{ required: true, message: "请选择上级部门", trigger: "blur" }],
  deptName: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    {
      min: 1,
      max: 10,
      message: '长度在 1 到 10 个字符',
      trigger: 'blur'
    }
  ],
};

const resetForm = () => {
  ruleFormRef.value?.resetFields();
  Object.assign(form, {
    deptName: "",
    description: "",
    parentId: undefined,
    id: undefined,
  });
};

const handleSave = async () => {
  try {
    if (!ruleFormRef.value) return;
    const isValid = await ruleFormRef.value.validate();
    if (!isValid) return;
    if (type.value === 'edit' && form.parentId == '-1') {
      form.parentId = 0;
    } 
    const res = type.value === 'edit' ? await updateDept(form) : await saveDept(form);
    if (res.resp_code === 200) {
      dialogFormVisible.value = false;
      ElMessage.success(res.resp_msg);
      emit("update");
    } else {
      ElMessage.error(res.resp_msg);
    }
  } catch (error) {
    console.error("保存失败:", error);
  }
};
const parentName = ref('')
const openDialog = async node => {
  resetForm();
  dialogFormVisible.value = true;
  if (node) {
    let res = await findParentDeptById({ id: node.id })
    parentName.value = res.deptName;
    Object.assign(form, node)
  };
  type.value = node ? 'edit' : 'creat'
};

defineExpose({ openDialog });
</script>

<template>
  <el-dialog v-model="dialogFormVisible" :title="type === 'creat' ? '新增部门' : '修改'" width="560">
    <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="100px" status-icon label-position="top">
      <el-form-item label="上级部门" prop="parentId" v-if="form.id != '-1'">
        <el-input v-if="parentName" v-model="parentName" disabled placeholder="请输入部门名称" />

        <el-tree-select v-else :props="{ children: 'children', label: 'deptName', value: 'id', }" placeholder="请选择上级部门"
          v-model="form.parentId" :data="listData" check-strictly :render-after-expand="false" node-key="id" />
      </el-form-item>
      <el-form-item label="部门名称" prop="deptName">
        <el-input v-model="form.deptName" placeholder="请输入部门名称" />
      </el-form-item>
      <el-form-item label="部门描述" prop="description">
        <el-input v-model="form.description" type="textarea" maxlength="100" show-word-limit placeholder="请输入部门描述" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave()"> 提交 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
